//
//  StudyAngleAdvSettingsViewController.swift
//  SitPosition
//
//  Created by apple on 2019/4/7.
//  Copyright © 2019 apple. All rights reserved.
//

import Foundation
import UIKit
import Cartography
import Toast_Swift


// 学习角度高级设置项
enum StudyAngleAdvSetting {
    case bodySlant(value: Int?)   // 默认：15，范围：5~25
    case headLowUp(value: Int?)   // 默认：140，范围：90~190
    case headLeft(value: Int?)    // 默认：20，范围：10~30
    case headRight(value: Int?)   // 默认：20，范围：10~30
    case headRotate(value: Int?)  // 默认：35，范围：25~45
    
    struct Default {
        static let bodySlantLimit: (Int, Int) = (5, 25)
        static let bodySlant: Int = 15
        
        static let headLowUpLimit: (Int, Int) = (90, 190)
        static let headLowUp: Int = 140
        
        static let headLRLimit: (Int, Int) = (10, 30)
        static let headLR: Int = 20
        
        static let headRotateLimit: (Int, Int) = (25, 45)
        static let headRotate: Int = 35
    }
    
    var title: String {
        switch self {
        case .bodySlant: return Strings.studySettingAdvanceSettingBodySlant
        case .headLowUp: return Strings.studySettingAdvanceSettingHeadLowUp
        case .headLeft: return Strings.studySettingAdvanceSettingHeadLeft
        case .headRight: return Strings.studySettingAdvanceSettingHeadRight
        case .headRotate: return Strings.studySettingAdvanceSettingHeadRotate
        }
    }
}

/**
 * 学习角度高级设置
 */
class StudyAngleAdvSettingsViewController : GKNavigationBarViewController {
    
    // 标题
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = Theme.Color.primaryDarkTextColor
        label.font = Theme.Font.boldFont(ofSize: 26)
        label.numberOfLines = 1
        label.lineBreakMode = .byTruncatingTail
        label.text = Strings.studySettingAdvanceSetting
        return label
    }()
    
    // 列表
    lazy var tableView: UITableView = {
        let table = UITableView(frame: CGRect.zero, style: UITableView.Style.plain)
        table.separatorColor = Theme.Color.primaryDarkSeperatorColor
        table.separatorInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
        table.dataSource = self
        table.delegate = self
        table.rowHeight = 52
        table.register(SettingInputTableViewCell.self, forCellReuseIdentifier: SettingInputTableViewCell.reusedIdentifier)
        table.tableFooterView = UIView()
        return table
    }()
    
    // 数据源
    private var settings: [StudyAngleAdvSetting] = []
    
    
    // MARK: - Object lifecycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 导航栏
        gk_navBackgroundColor = UIColor.clear
        gk_navLeftBarButtonItem = UIBarButtonItem(imageName: "ic_nav_back_black", target: self, action: #selector(_backButtonTapped))
        
        // 查看使用说明
        let rightBtn = UIButton(type: UIButton.ButtonType.custom)
        rightBtn.bounds = CGRect(x: 0, y: 0, width: 120, height: 44)
        rightBtn.setTitle(Strings.studySettingAdvanceSettingViewUserGuide, for: UIControl.State.normal)
        rightBtn.setTitleColor(Theme.Color.primaryBlueColor, for: UIControl.State.normal)
        rightBtn.titleLabel?.font = Theme.Font.regularFont(ofSize: 16)
        rightBtn.addTarget(self, action: #selector(_userGuideButtonTapped), for: UIControl.Event.touchUpInside)
        gk_navRightBarButtonItem = UIBarButtonItem(customView: rightBtn)
        
        // 子视图
        view.addSubviews([
            titleLabel,
            tableView
        ])
        _setupContraints()
        view.backgroundColor = UIColor.white
        
        // 刷新数据
        _rebuildSettings()
        tableView.reloadData()
    }
}

// MARK: - UITableViewDataSource / UITableViewDelegate

extension StudyAngleAdvSettingsViewController : UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return settings.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: SettingInputTableViewCell.reusedIdentifier, for: indexPath) as! SettingInputTableViewCell
        
        let data: StudyAngleAdvSetting = settings[indexPath.row]
        cell.textLabel?.text = data.title
        switch data {
        case let .bodySlant(value):
            cell.value = String(format: "%d", value ?? StudyAngleAdvSetting.Default.bodySlant)
            cell.onInputChanged = { [unowned self] newValue in
                var intValue: Int? = newValue != nil ? Int(newValue!):nil
                if let value = intValue {
                    if value < StudyAngleAdvSetting.Default.bodySlantLimit.0 &&
                        value > StudyAngleAdvSetting.Default.bodySlantLimit.1 {
                        intValue = nil
                    }
                }
                self.settings[indexPath.row] = StudyAngleAdvSetting.bodySlant(value: intValue)
                Preferences.bodySlantThreshold = intValue
            }
        case let .headLowUp(value):
            cell.value = String(format: "%d", value ?? StudyAngleAdvSetting.Default.headLowUp)
            cell.onInputChanged = { [unowned self] newValue in
                var intValue: Int? = newValue != nil ? Int(newValue!):nil
                if let value = intValue {
                    if value < StudyAngleAdvSetting.Default.headLowUpLimit.0 &&
                        value > StudyAngleAdvSetting.Default.headLowUpLimit.1 {
                        intValue = nil
                    }
                }
                self.settings[indexPath.row] = StudyAngleAdvSetting.headLowUp(value: intValue)
                Preferences.headLowUpThreshold = intValue
            }
        case let .headLeft(value):
            cell.value = String(format: "%d", value ?? StudyAngleAdvSetting.Default.headLR)
            cell.onInputChanged = { [unowned self] newValue in
                var intValue: Int? = newValue != nil ? Int(newValue!):nil
                if let value = intValue {
                    if value < StudyAngleAdvSetting.Default.headLRLimit.0 &&
                        value > StudyAngleAdvSetting.Default.headLRLimit.1 {
                        intValue = nil
                    }
                }
                self.settings[indexPath.row] = StudyAngleAdvSetting.headLeft(value: intValue)
                Preferences.headLeftThreshold = intValue
            }
        case let .headRight(value):
            cell.value = String(format: "%d", value ?? StudyAngleAdvSetting.Default.headLR)
            cell.onInputChanged = { [unowned self] newValue in
                var intValue: Int? = newValue != nil ? Int(newValue!):nil
                if let value = intValue {
                    if value < StudyAngleAdvSetting.Default.headLRLimit.0 &&
                        value > StudyAngleAdvSetting.Default.headLRLimit.1 {
                        intValue = nil
                    }
                }
                self.settings[indexPath.row] = StudyAngleAdvSetting.headRight(value: intValue)
                Preferences.headRightThreshold = intValue
            }
        case let .headRotate(value):
            cell.value = String(format: "%d", value ?? StudyAngleAdvSetting.Default.headRotate)
            cell.onInputChanged = { [unowned self] newValue in
                var intValue: Int? = newValue != nil ? Int(newValue!):nil
                if let value = intValue {
                    if value < StudyAngleAdvSetting.Default.headRotateLimit.0 &&
                        value > StudyAngleAdvSetting.Default.headRotateLimit.1 {
                        intValue = nil
                    }
                }
                self.settings[indexPath.row] = StudyAngleAdvSetting.headRotate(value: intValue)
                Preferences.headRotateThreshold = intValue
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        switch section {
        case 0:
            // 复位
            let resetBtn = UIButton(type: UIButton.ButtonType.custom)
            resetBtn.bounds = CGRect(x: 0, y: 0, width: 100, height: 44)
            resetBtn.setTitle(Strings.studySettingAdvanceSettingReset, for: UIControl.State.normal)
            resetBtn.setTitleColor(Theme.Color.warningColor, for: UIControl.State.normal)
            resetBtn.titleLabel?.font = Theme.Font.regularFont(ofSize: 16)
            resetBtn.addTarget(self, action: #selector(_resetButtonTapped), for: UIControl.Event.touchUpInside)
            return resetBtn
        default: return nil;
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        switch section {
        case 0: return 64
        default: return 0;
        }
    }
}

// MARK: - Private Methods

extension StudyAngleAdvSettingsViewController {
    
    // 设置视图约束
    func _setupContraints() {
        // titleLabel
        constrain(titleLabel, gk_navigationBar, view) { v, sibling, parent in
            v.top == sibling.bottom + 19
            v.left == parent.left + 16
            v.right == parent.right - 16
            v.height == 25
        }
        
        // tableView
        constrain(tableView, titleLabel, view) { v, sibling, parent in
            v.top == sibling.bottom + 20
            v.left == parent.left
            v.right == parent.right
            v.bottom == parent.bottom
        }
    }
    
    // 重新Build数据源
    private func _rebuildSettings() {
        settings = [
            StudyAngleAdvSetting.bodySlant(value: Preferences.bodySlantThreshold ?? StudyAngleAdvSetting.Default.bodySlant),
            StudyAngleAdvSetting.headLowUp(value: Preferences.headLowUpThreshold ?? StudyAngleAdvSetting.Default.headLowUp),
            StudyAngleAdvSetting.headLeft(value: Preferences.headLeftThreshold ?? StudyAngleAdvSetting.Default.headLR),
            StudyAngleAdvSetting.headRight(value: Preferences.headRightThreshold ?? StudyAngleAdvSetting.Default.headLR),
            StudyAngleAdvSetting.headRotate(value: Preferences.headRotateThreshold ?? StudyAngleAdvSetting.Default.headRotate)
        ]
    }
    
    // 返回按钮点击事件
    @objc func _backButtonTapped() {
        if presentingViewController != nil {
            dismiss(animated: true, completion: nil)
        } else {
            navigationController?.popViewController(animated: true)
        }
    }
    
    // 查看使用说明
    @objc func _userGuideButtonTapped() {
        let vc = StudyUserGuideViewController()
        navigationController?.pushViewController(vc, animated: true)
    }
    
    // 重置
    @objc func _resetButtonTapped() {
        Preferences.bodySlantThreshold = nil
        Preferences.headLowUpThreshold = nil
        Preferences.headLeftThreshold = nil
        Preferences.headRightThreshold = nil
        Preferences.headRotateThreshold = nil
        _rebuildSettings()
        tableView.reloadData()
        self.view.makeToast(Strings.studySettingAdvanceSettingResetSuccess)
    }
}
